<?php
/**
 * Created by PhpStorm.
 * User: iamya
 * Date: 2017/11/27
 * Time: 8:36
 */

namespace app\home\controller;


use app\common\LeadsModel;
use app\common\LeadsRecordModel;
use think\Exception;
use think\Request;
use think\Validate;

class LeadsController extends BaseController
{
    private $leadsModel;
    private $leadsRecordModel;
    private $userInfo;

    public function __construct(Request $request = null)
    {
        parent::__construct($request);
        $this->leadsModel = new LeadsModel();
        $this->leadsRecordModel = new LeadsRecordModel();
        $this->userInfo = $this->getDduser();
    }

    /**
     * 线索列表以及查询
     */
    public function index()
    {
        $data = $this->request->param();
        $map = [];
        if (!empty($data['owner_userid'])) {
            $map['owner_userid'] = $data['owner_userid'];
        }
        if (!empty($data['creator_userid'])) {
            $map['creator_userid'] = $data['creator_userid'];
        }
        if (!empty($data['name'])) {
            $map['name'] = ['like', '%' . $data['name'] . '%'];
        }
        if (!empty($data['position'])) {
            $map['position'] = ['like', '%' . $data['position'] . '%'];
        }
        if (!empty($data['contacts_name'])) {
            $map['contacts_name'] = ['like', '%' . $data['contacts_name'] . '%'];
        }
        if (!empty($data['mobile'])) {
            $map['mobile'] = $data['mobile'];
        }
        switch ($data['leads_status']){
            case 1:/*我近7日跟进*/
                $map['owner_userid']=$this->getDduser()['userid'];
                $this->leadsModel->whereTime('have_time','-7 days');
                break;
            case 2:/*本周新增*/
                $this->leadsModel->whereTime('create_time','week');
                break;
        }
        $list = $this->leadsModel->where($map)->paginate(5, false, ['query' => $data]);
        $sql=$this->leadsModel->getLastSql();
        foreach ($list as $k=>$v){
            $list[$k]['surname']=msubstr($v['name'], 0, 1, "utf-8", false);
            $list[$k]['record_count']=$this->leadsRecordModel->where('leads_id',$v['leads_id'])->count();
            $recordInfo=$this->leadsRecordModel->where('leads_id',$v['leads_id'])->order('create_time desc')->find();
            $list[$k]['create_name']=date('Y-m-d',$v['create_time']);
            $list[$k]['last_time']=date('Y-m-d',$recordInfo['create_time']);
            $list[$k]['last_name']=get_field_value('user', 'name', ['userid'=>$recordInfo['owner_userid']]);
        }
        return $this->callBack(0, $sql, $list);
    }

    /**
     * 获取单条线索信息
     * @return \think\response\Json
     */
    public function getOneInfo()
    {
        $data = $this->request->param();
        $map = [];
        if (!empty($data['leads_id'])) {
            $map['leads_id'] = $data['leads_id'];
        }
        if (!empty($data['mobile'])) {
            $map['mobile'] = $data['mobile'];
        }
        $info = $this->leadsModel->where($map)->find();
        if (empty($info)) {
            return $this->callBack(2, $this->leadsModel->getError());
        } else {
            $info['record_count']=$this->leadsRecordModel->where('leads_id',$info['leads_id'])->count();
            $recordInfo=$this->leadsRecordModel->where('leads_id',$info['leads_id'])->order('create_time desc')->find();
            $info['create_time']=date('Y-m-d',$info['create_time']);
            $info['last_time']=date('Y-m-d',$recordInfo['create_time']);
            $info['last_name']=get_field_value('user', 'name', ['userid'=>$recordInfo['owner_userid']]);
            return $this->callBack(0, '信息检索成功', $info);
        }
    }

    /**
     * 线索添加
     */
    public function add()
    {
        $data = $this->request->param();
        if($this->leadsModel->where('mobile',$data['mobile'])->find()){
            $this->error('已有线索信息，请维护跟进');
        }
        $data += [
            'owner_userid' => $this->userInfo['userid'],
            'creator_userid' => $this->userInfo['userid'],
            'is_deleted' => 0,
            'delete_userid' => '',
            'delete_time' => 0,
            'is_transformed' => 0,
            'customer_id' => 0,
            'business_id' => 0,
        ];
        $validate = new Validate([
            ['creator_userid', 'require', '请先登录'],
            ['name', 'require', '请输入客户姓名'],
            ['mobile', 'require', '请输入客户联系方式'],
        ]);
        $result = $validate->check($data);
        if (true !== $result) {
            return $this->callBack(1, $validate->getError());
        }
        if ($this->leadsModel->save($data)) {
            return $this->callBack(0, '线索添加成功', url('home/Index/index',['folder'=>'leads','file'=>'info','leads_id'=>$this->leadsModel->getLastInsID()]));
        } else {
            return $this->callBack(2, $this->leadsModel->getError());
        }
    }

    /**
     * 线索修改
     */
    public function edit()
    {
        $data = $this->request->param();
        $validate = new Validate([
            ['leads_id', 'require', '请选择修改的记录'],
            ['name', 'require', '请输入客户姓名'],
            ['mobile', 'require', '请输入客户联系方式'],
        ]);
        $result = $validate->check($data);
        if (true !== $result) {
            $this->callBack(1, $validate->getError());
        }
        if ($this->leadsModel->data($data)->save()) {
            return $this->callBack(0, '线索修改成功', $data['leads_id']);
        } else {
            return $this->callBack(2, $this->leadsModel->getError());
        }
    }

    /**
     * 线索删除
     */
    public function del()
    {
        $leadsId=$this->request->param('leads_id',0);
        try{
            $this->leadsModel->save(['leads_id'=>$leadsId,'is_deleted'=>1,'delete_userid'=>$this->userInfo['userid'],'delete_time'=>time()]);
        }catch (Exception $e){
            return $this->callBack(2,$e->getMessage());
        }
        return $this->callBack(0,'线索删除成功',$leadsId);
    }

    /**
     * 添加流水
     */
    public function addRecord()
    {
        $data = $this->request->param();
        $data['owner_userid'] = $this->userInfo['userid'];
        $data['create_time'] = time();
        $validate = new Validate([
            ['leads_id', 'require', '请选择线索'],
            ['owner_userid', 'require', '请先登录'],
            ['create_time', 'require', '请确认时间'],
//            ['record_title','require','请输入流水标题']
            ['record_remark', 'require', '请输入流水备注']
        ]);
        $result = $validate->check($data);
        if (true !== $result) {
            return $this->callBack(1, $validate->getError());
        }
        if ($this->leadsRecordModel->data($data)->save()) {
            $this->leadsModel->where('leads_id',$data['leads_id'])->setField(['have_time'=>time()]);
            return $this->callBack(0, '线索跟进内容添加成功',url('home/Index/index',['folder'=>'leads','file'=>'info','leads_id'=>$data['leads_id']]));
        } else {
            return $this->callBack(2, $this->leadsRecordModel->getError());
        }
    }

    /**
     * 获取流水列表
     */
    public function getRecord()
    {
        $data = $this->request->param();
        $map = [];
        if (!empty($data['word'])) {//流水查找，多个单词用空格隔开
            $words = explode(' ', $data['word']);
            foreach ($words as $word) {
                $map['record_title|record_remark'][] = ['like', '%' . $word . '%'];
            }
            $map['record_title|record_remark'][] = 'or';
        }
        if(!empty($data['leads_id'])){
            $map['leads_id']=$data['leads_id'];
        }
        $startTime = $this->request->param('start_time', '1970-01-01 08:00:01');
        $endTime = $this->request->param('end_time', '5138-11-16 17:46:39');
        $map['create_time'] = ['between', [strtotime($startTime), strtotime($endTime)]];
        $list = $this->leadsRecordModel->where($map)->order('create_time desc')->paginate(12, false, ['query' => $data]);
        foreach ($list as $k=>$v){
            $list[$k]['name']=get_field_value('user', 'name', ['userid'=>$v['owner_userid']]);
            $list[$k]['date']=date('Y-m-d',$v['create_time']);
            $list[$k]['time']=date('H:i',$v['create_time']);
        }
        return $this->callBack(0, '流水加载完成', $list);
    }


}